package cn.qingfeng.nio.blocking.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * nio阻塞模式，服务端代码与非阻塞的略有不同
 */
public class BioClient {

    public static void main(String[] args) throws IOException {
        // 打开一个Socket通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
        // 不同点1：
        socketChannel.configureBlocking(true);

        // 准备要发送的数据
        String message = "Hello, NIO Server!";
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());

        // 发送数据到服务器
        // - 不同点2：不用循环判断了
        socketChannel.write(buffer);

        // 准备接收来自服务器的响应
        // - 不同点3：不用循环判断了
        buffer.clear();
        int bytesRead = socketChannel.read(buffer);

        // 非阻塞模式下不能直接取值，要循环判断读到的数据是否为空
        if (bytesRead == -1) {
            System.out.println("连接已关闭");
        } else if (bytesRead == 0) {
            System.out.println("服务端还没有回应，稍等一会儿……");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        } else {
            System.out.println("读到了数据，开始处理：");
            buffer.flip();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            String response = new String(bytes);

            System.out.println("Received response from server: " + response);

        }

        // 关闭通道
        socketChannel.close();
    }
}